<template>
  <div>
    <div class="query-form">
    <el-form
      :model="queryForm"
      ref="queryFormRef"
      label-width="100px"
      :inline="true"
    >

      <el-form-item label="供应商名称">
        <el-input v-model="queryForm.vender" placeholder="请输入供应商名称或供应商编码" style="width: 240px" />
      </el-form-item>
      <el-form-item label="核销申请人">
        <el-input v-model="queryForm.creater" placeholder="请输入创建人" style="width: 200px" />
      </el-form-item>

      <el-form-item label="创建日期">
        <el-date-picker
          v-model="currentDate"
          type="daterange"
          range-separator="-"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          style="width: 300px"
        />
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="load">查询</el-button>
        <el-button type="warning"  @click="openBatchDialog">
      批量审核
    </el-button>
      </el-form-item>

      <el-form-item label="合计可补金额">
        <el-input v-model="queryForm.actRebAmtTotal" placeholder="请勾选数据" style="width: 160px" />
      </el-form-item>
      <el-form-item label="合计应收金额">
        <el-input v-model="queryForm.rebAmtTotal" placeholder="请勾选数据" style="width: 160px" />
      </el-form-item>
    </el-form>
  </div>

      <el-table
      :data="tableData"
      border
      style="width: 100%"
      :header-cell-style="{
        color: '#333',
        backgroundColor: '#eaf4ff',
        height: '20px'  // 表头固定高度
      }"
      @selection-change="handleSelectionChange"
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '5px 0' }"
    >
        <el-table-column type="selection" width="45" />
        <el-table-column
          prop="createDate"
          label="核销申请时间"
          width="200"
          :formatter="formatDate2"
        />
        <el-table-column prop="venderName" label="供应商名称" width="220" />
        <el-table-column prop="createrName" label="核销申请人" width="100" />
        <el-table-column prop="actRebAmt" label="可补金额" width="100" />
        <el-table-column prop="rebAmt" label="应收金额" width="100" />
        <el-table-column prop="applyAmt" label="申请金额" width="100" />
        <!-- <el-table-column prop="buyerName" label="采购审核人" width="100" /> -->
        <!-- <el-table-column prop="comfirmDate" label="采购审核时间" :formatter="formatDate2" width="150" /> -->
        <el-table-column prop="operaterName" label="财务审核人" width="100" />
        <el-table-column prop="operateDate" label="财务审核时间" :formatter="formatDate2" width="200" />
        <el-table-column prop="opFlagName" label="单据状态" width="90" />
        <!-- <el-table-column prop="purMemo" label="采购备注" width="180" /> -->
        <el-table-column prop="opMemo" label="财务备注" width="250" />
        <el-table-column prop="purTaxRate" label="ERP核销单号" />
        <el-table-column label="明细" width="80">
          <template #default="scope">
            <el-button
              type="text"
              @click="detail(scope.row)"
            >
             <el-icon style="font-size: 25px;"><Search /></el-icon>
          </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button
              type="primary"
              @click="openPolicyDialog(scope.row)"
            >审核</el-button>
          </template>
        </el-table-column>

      </el-table>
  </div>
  <div class="card">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total,sizes, prev, pager, next"
          :total="data.total"
          :page-sizes="[20, 40, 80]"
          @current-change="load"
          @size-change="load"
      />
  </div>
      <!-- 查看明细弹窗 -->
    <el-dialog v-model="showDetailDialog" title="明细详情" width="1500px">
      <el-table
      :data="tableDataList"
      border
      style="width: 100%;margin-bottom: 20px;"
      :header-cell-style="{
        color: '#333',
        backgroundColor: '#eaf4ff',
        height: '20px'  // 表头固定高度
      }"
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '5px 0' }"
    >
        <el-table-column prop="clientPartyId" label="客户ID" width="100" />
        <el-table-column prop="clientPartyName" label="客户名称" width="180" />
        <el-table-column prop="sscOrderLinesLotsId" label="供应商代码" width="100" />
        <el-table-column prop="venderName" label="供应商名称" width="180" />
        <el-table-column prop="saleOrg" label="销售部门" width="100" />
        <el-table-column prop="buyerName" label="采购员" width="80" />
        <el-table-column prop="comGoodsId" label="商品ID" width="80" />
        <el-table-column prop="goodsOpcode" label="商品编码" width="100" />
        <el-table-column prop="goodsName" label="商品名称" width="100" />
        <el-table-column prop="goodsDesc" label="商品规格" width="120" />
        <el-table-column prop="unitName" label="单位" width="60" />
        <el-table-column prop="qty" label="数量" width="60" />
        <el-table-column prop="taxPrice" label="含税进价" width="80" />
        <el-table-column prop="purPrice" label="进价" width="100" />
        <el-table-column prop="taxRate" label="税率" width="100" />
        <el-table-column prop="rebAmt" label="应收金额" width="100" />
        <el-table-column prop="actRebAmt" label="可补金额" width="100" />
        <el-table-column prop="lotNo" label="批号" width="110" />
        <el-table-column
          prop="produceDate"
          label="生产日期"
          width="100"
          :formatter="formatDate"
        />
        <el-table-column
          prop="expireDate"
          label="有效期"
          width="100"
          :formatter="formatDate"
        /><el-table-column
          prop="impDate"
          label="生成日期"
          width="100"
          :formatter="formatDate"
        />
        <el-table-column prop="comGoodsBatchId" label="批次号" width="100" />

        <el-table-column prop="productLocation" label="生产厂家" width="200" />
        <el-table-column prop="channelOpcode" label="渠道号" width="100" />
        <el-table-column prop="chcanelName" label="渠道商" width="90" />
        <el-table-column prop="hnyyPurRebateListId" label="政策ID" width="90" />
        <el-table-column prop="checkerName" label="确权人" width="90" />
        <el-table-column
          prop="checkDate"
          label="确权时间"
          width="100"
          :formatter="formatDate"
        />

        <el-table-column prop="opFlagName" label="单据状态" width="120" />
      </el-table>
    </el-dialog>

    <!-- 单条审核弹窗 -->
    <el-dialog v-model="showAuditDialog" title="财务审核" width="400px">
      <el-input v-model="audit.memo" placeholder="请输入审核备注" type="textarea" rows="3" />
      <template #footer>
        <el-button type="primary" @click="submitAudit(1)">审核通过</el-button>
        <el-button type="primary" @click="submitAudit(3)">审核不通过</el-button>
      </template>
    </el-dialog>

    <!-- 批量审核弹窗 -->
    <el-dialog v-model="showBatchDialog" title="批量审核" width="400px">
      <el-input v-model="batch.memo" placeholder="请输入审核备注" type="textarea" rows="3" />
      <template #footer>
        <el-button type="warning" @click="submitBatchAudit(1)">批量审核通过</el-button>
        <el-button type="warning" @click="submitBatchAudit(3)">批量审核不通过</el-button>
      </template>
    </el-dialog>
</template>

<script setup>
import { ref,reactive,nextTick,watch } from 'vue';
import request from '@/utils/request';
import dayjs from "dayjs";
import { ElLoading } from 'element-plus';
import {ElMessage } from 'element-plus'
import {currentDate} from '../../utils/time.js';
import {Search } from "@element-plus/icons-vue";


// 查询条件
const queryForm=reactive({
  vender:'',
  creater:'', // 创建人
})
// 政策维护数据
const data=ref({
  pageNum:1,
  pageSize:20,
  total:0
})

const formatDate2=(row, column, cellValue)=>{
   if (!cellValue) return '';
    // 转换成 Date 对象
    const date = new Date(cellValue);
    // 格式化
    return `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')} `
         + `${String(date.getHours()).padStart(2,'0')}:${String(date.getMinutes()).padStart(2,'0')}:${String(date.getSeconds()).padStart(2,'0')}`;
}

const tableData = ref([]);
const load=()=>{
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '数据加载中，请稍候...',
    background: 'rgba(255, 255, 255, 0.7)',
  });
  const startDate = dayjs(currentDate.value[0]).format('YYYY-MM-DD')
  const endDate = dayjs(currentDate.value[1]).format('YYYY-MM-DD')
  request.get('/account/getHxList',{
    params:{
      pageNum: data.value.pageNum,
      pageSize: data.value.pageSize,
      venderId: queryForm.vender,
      creater: queryForm.creater,
      startDate:startDate,
      endDate:endDate,
      key:1
    }
  }).then((res) => {
    console.log('res',res)
    if (res.code === 200) {
      tableData.value = res.data.list
      data.value.pageNum = res.data.pageNum
      data.value.total = res.data.total;
    } else {
      console.error('Error loading data:', res.message);
    }
  }) .catch((err) => {
      console.error('请求失败', err);
      ElMessage.error('加载失败，请稍后再试');
    })
    .finally(() => {
      loadingInstance.close();
    });
}
load();

// 明细数据
const showDetailDialog = ref(false);
const tableDataList = ref([]);


// 单条审核
const showAuditDialog = ref(false);
const currentAuditId = ref(null);
const audit = reactive({ memo: '' });

// 多选
const multipleSelection = ref([]);
const showBatchDialog = ref(false);
const batch = reactive({ memo: '' });
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const detail = (row) => {
  showDetailDialog.value = true;
  request.get('/account/getHxListById', {
      params: {
        id: row.hnyyPurRebateSaleHxId
      }
  }).then(res => {
    if (res.code === 200) {
      const resultData = res.data;
      tableDataList.value = Array.isArray(resultData) ? resultData : [resultData];
    }
  });
};
// 单条审核弹窗
const openPolicyDialog = (row) => {
  currentAuditId.value = row.hnyyPurRebateSaleHxId;
  audit.memo = '';
  showAuditDialog.value = true;
};

// 提交单条审核
const submitAudit = (key) => {
  request.get('/account/saleCheck', {
    params:{
      id: currentAuditId.value,
      memo: audit.memo,
      key:key
    }

  }).then(res => {
    if (res.code === 200) {
      ElMessage.success('审核成功');
      showAuditDialog.value = false;
      load();
    }
  });
};

// 批量审核弹窗
const openBatchDialog = () => {
  batch.memo = '';
  showBatchDialog.value = true;
};

// 批量审核提交
const submitBatchAudit = (key) => {
  // eslint-disable-next-line @typescript-eslint/no-unused-expressions
  multipleSelection.value.length===0 && ElMessage.warning('请先选择要审核的单据');
  if (multipleSelection.value.length===0) return;
  console.log('multipleSelection.value',multipleSelection.value)
 multipleSelection.value.forEach(item => {
    request.get('/account/saleCheck', {
      params:{
        id: item.hnyyPurRebateSaleHxId,
        memo: batch.memo,
        key:key
      }
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success(`单据ID ${item.hnyyPurRebateSaleHxId} 审核成功`);
        showBatchDialog.value = false;
        load();
      }
    });
  });
};

</script>

<style>

</style>
